package com.turnengine.client.local.unit.storage;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.turnengine.client.local.unit.bean.IStorageGroup;
import com.turnengine.client.local.unit.bean.IStorageItem;
import com.turnengine.client.local.unit.bean.IUnit;

public class StorageCache implements IStorageCache {

	private final Map<Integer, IStorageGroupSet> unitIdToStorageSetMap = new ConcurrentHashMap<Integer, IStorageGroupSet>();

	@Override
	public List<IStorageGroup> getStorageGroups() {
		List<IStorageGroup> list = new ArrayList<IStorageGroup>();
		for (IStorageGroupSet set : unitIdToStorageSetMap.values()) {
			list.addAll(set.getStorageGroups());
		}
		return list;
	}

	@Override
	public List<IStorageItem> getStorageItems() {
		List<IStorageItem> list = new ArrayList<IStorageItem>();
		for (IStorageGroupSet set : unitIdToStorageSetMap.values()) {
			list.addAll(set.getStorageItems());
		}
		return list;
	}

	@Override
	public void addStorageGroup(IStorageGroup group) {
		int unitId = group.getParent();
		IStorageGroupSet set = unitIdToStorageSetMap.get(unitId);
		if (set == null) {
			set = new StorageGroupSet(unitId);
			unitIdToStorageSetMap.put(unitId, set);
		}
		set.addStorageGroup(group);
	}

	@Override
	public void addStorageItem(IStorageItem item) {
		int unitId = item.getParent();
		IStorageGroupSet set = unitIdToStorageSetMap.get(unitId);
		if (set == null) {
			throw new IllegalArgumentException("attempt to add item without first adding group, item=" + item);
		}
		set.addStorageItem(item);
	}

	@Override
	public void addStorageGroups(Collection<IStorageGroup> groups) {
		for (IStorageGroup group : groups) {
			addStorageGroup(group);
		}
	}

	@Override
	public void addStorageItems(Collection<IStorageItem> items) {
		for (IStorageItem item : items) {
			addStorageItem(item);
		}
	}

	@Override
	public IStorageGroupSet getStorageGroupSet(int unitId) {
		IStorageGroupSet set = unitIdToStorageSetMap.get(unitId);
		if (set == null) {
			set = new StorageGroupSet(unitId);
		}
		return set;
	}

	@Override
	public IStorageGroupSet getStorageGroupSet(IUnit unit) {
		return getStorageGroupSet(unit.getId());
	}

}
